import React, { useMemo, useState } from "react";
import Popover from "components/Popover";
import { changeDate } from "utils/date";
import { deleteRoulette } from "api/backend";
import "./index.less";

export default function JackpotBox({ rouletteInfo,potLength }) {
  const { prizes, release_prize_at, roulette_id } = rouletteInfo;
  const [delAppear, setDelAppear] = useState(false);
  const [title, setTitle] = useState("");
  const [isCancel, setIsCancel] = useState(false);
  const prizeDate = useMemo(
    () => changeDate(release_prize_at),
    [release_prize_at]
  );

  // 取消删除转盘
  const hidePopover = () => {
    setDelAppear(false);
  };

  // 删除操作
  const handleDelete = () => {
    setTitle("是否删除此奖池");
    setIsCancel(true);
    setDelAppear(true);
  }

  // 删除转盘
  const delJackpot = async () => {
    hidePopover();
    // 防止删除最后一个转盘
    if(potLength === 1) {
      setTitle("不能删除，因为只能留下一个转盘!!!");
      setDelAppear(true);
      return;
    }
    await deleteRoulette(roulette_id);
    // 刷新页面
    window.location.reload();
  };
  return (
    <li className="jackpot-box">
      <img className="theme-img" src={prizes[0].picture_url} alt="" />
      <div className="time">
        <p>开奖时间:</p>
        <p className="prize-time">{prizeDate}</p>
        <button className="delete" onClick={handleDelete}>
          删除
        </button>
      </div>
      <Popover
        appear={delAppear}
        title={title}
        ensureHandle={delJackpot}
        isCancel={isCancel}
        cancelHandle={hidePopover}
      />
    </li>
  );
}
